//
//  StockLineViewController.m
//  RedManStock
//
//  Created by lanou3g on 15/7/26.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "StockLineViewController.h"
#import "MyHandle.h"
#import "ParameterHeader.h"
#import "StockVolume.h"
#import "UIDefine.h"
#import "MBProgressHUD.h"
@interface StockLineViewController ()

@property (nonatomic,retain) NSMutableArray *stockArray;
@property (nonatomic,assign) BOOL simpleOrNot; //用来切换是三个视图还是两个
@property (nonatomic) MBProgressHUD * progressHUD;
@end

@implementation StockLineViewController

@synthesize candleChart;
//@synthesize autoCompleteView;
//@synthesize toolBar;
//@synthesize candleChartFreqView;
//@synthesize autoCompleteDelegate;
@synthesize timer;
@synthesize chartMode;
@synthesize tradeStatus;
@synthesize lastTime;
//@synthesize status;
@synthesize req_freq;
@synthesize req_type;
//@synthesize req_url;
@synthesize req_security_id;


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.simpleOrNot=YES;
    
    self.view.backgroundColor=[UIColor blackColor];
    
    self.chartMode  = 1; //1,candleChart
    self.tradeStatus= 1;
    self.req_freq=@"volume";   //这里表示什么类型的数据
    self.req_type=@"day";      //这里表示什么日K，周K，还是年K
    
    //    self.req_freq   = @"d";   //表示日k，周k，还是年k
    //    self.req_type   = @"H";   //目前没弄明白，但值一般为H T L
    //    self.req_url    = @"http://ichart.yahoo.com/table.csv?s=%@&&g=%@";
    
    //这样设置myView的frame是为了，所普的视图能响应
        UIView *myView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.height, self.view.bounds.size.height)];
    
    //    最下方切换K线图的3个button
    self.headControlView=[[HeadControlView alloc]initWithFrame:CGRectMake(self.view.bounds.size.height/4, self.view.bounds.size.width-30, self.view.bounds.size.height*3/4, 30) titleArray:@[@"日K",@"周K",@"月K"]];
    //换背景颜色
    self.headControlView.backgroundColor=[UIColor colorWithRed:0.416 green:0.105 blue:0.305 alpha:1.000];
    for (UIButton *button in self.headControlView.buttonArray) {
        [button addTarget:self action:@selector(bigClickButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UIButton *backButton=[UIButton buttonWithFrame:CGRectMake(20, self.view.bounds.size.width-30, 70, 30) normalTitle:@"切换竖屏" addTarget:self action:@selector(backToStockHome:)];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backButton.layer.borderWidth=1;
    backButton.layer.borderColor=[UIColor grayColor].CGColor;
    backButton.titleLabel.font=[UIFont systemFontOfSize:17];
//    [self.view addSubview:backButton];
    
    UIButton *changeButton=[UIButton buttonWithFrame:CGRectMake(self.view.bounds.size.height/4-50, self.view.bounds.size.width-30, 50, 30) normalTitle:@"详细" addTarget:self action:@selector(changeSectionShow:)];
    
    [changeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    changeButton.layer.borderWidth=1;
    changeButton.layer.borderColor=[UIColor grayColor].CGColor;
    changeButton.titleLabel.font=[UIFont systemFontOfSize:15];
    changeButton.backgroundColor=[UIColor colorWithRed:0.416 green:0.105 blue:0.305 alpha:1.000];
//    [self.view addSubview: changeButton];
    
    
    //进来就设置nowLocation为0，这样就是直接选中了日k图
    self.headControlView.nowLocation=0;
//    [self.view addSubview:self.headControlView];
    //    [myView addSubview:self.headControlView];
    
    //    [self.headControlView release];
    //竖屏的frame
    //    self.candleChart = [[Chart alloc] initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height-60-30)];
    //横屏的frame
    self.candleChart = [[Chart alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width-30)];
    
//    myView.center=self.view.center;
    [myView addSubview:backButton];
    [myView addSubview: changeButton];
    [myView addSubview:self.headControlView];
    [myView addSubview:candleChart];
    [self.view addSubview:myView];
    myView.layer.anchorPoint=CGPointMake(0, 0);
    myView.layer.position=CGPointMake(0,0);
    myView.transform = CGAffineTransformMakeRotation(M_PI_2);
//    在此现有基础上来做平移，注意transForm旋转了的话，x，y轴也跟着旋转
    myView.transform=CGAffineTransformTranslate(myView.transform, 0, -self.view.bounds.size.width);
    
    [self.headControlView release];
    [candleChart release];
    [backButton release];
    [changeButton release];
    
    //在这之前可以添加一些其他视图
    [self initChart];
    
    //进来先请求数据
    [self loadNewDataWithType:self.req_type freq:self.req_freq];
    
    
    //    myView.transform = CGAffineTransformMakeRotation(M_PI_2);
    //    [self.view addSubview:myView];
    
}

//http://api.gongniucaijing.com/stock/klineEx?code=600369&complete=0&idfa=7B7C9B42-5C18-4EEB-A0F8-6708DE081AAE&machine=iPhone%205&norm=volume&number==200&offset=0&os=iPhone%20OS%208.2&platform=1&protocolVersion=1.0&qudao=0000001&resolution=640%2A1136&rights=0&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&type=day&uuid=BULLSTOCK-79460017-C3E5-45EC-B98C-1DD541A61127&version=1.9.0&versionCode=190

- (void)loadNewDataWithTime{
    
}

- (void)loadNewDataWithType:(NSString *)type
                       freq:(NSString *)freq{
    
    //====== 将原来getData中隐藏的方法，填写在了这里
#pragma mark  通过chartMode来判断第二个区是否显示，如果设置为NO，则它就不显示了
    //    if(chartMode == 0){
    //        [self.candleChart getSection:2].hidden = YES;
    //
    //    }else{
    //        [self.candleChart getSection:2].hidden = NO;
    //        //如果添加上这句，这个区就不显示了
    //        //                [self.candleChart getSection:0].hidden=YES;
    //        //        [self.candleChart getSection:1].hidden=YES;
    //        //        [self.candleChart getSection:2].hidden=YES;
    //    }
    
    //    if(_simpleOrNot == YES){
    //        [self.candleChart getSection:2].hidden = YES;
    //
    //    }else{
    //        [self.candleChart getSection:2].hidden = NO;
    
    self.progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *url=@"http://api.gongniucaijing.com/stock/klineEx";
    
    [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
        NSDictionary *dic=@{@"code":self.code,
                            @"type":self.req_type,
                            @"norm":self.req_freq,
                            @"number":@"300",
                            @"offset":@"0",
                            @"token":Token,
                            @"complete":@"0"};
        return dic;
    } successBlock:^(NSDictionary *responseDic) {
        
        NSArray *listsArray=[[responseDic objectForKey:@"data"] objectForKey:@"lists"];
        NSMutableArray *tempArray=[NSMutableArray array];
        for (NSDictionary *dic in listsArray) {
            StockVolume *stockVolume=[[StockVolume alloc]init];
            stockVolume.high=[[dic objectForKey:@"high"] stringValue];
            stockVolume.low=[[dic objectForKey:@"low"] stringValue];
            stockVolume.open=[[dic objectForKey:@"open"] stringValue];
            stockVolume.close=[[dic objectForKey:@"close"] stringValue];
            stockVolume.MA5=[[dic objectForKey:@"MA5"] stringValue];
            stockVolume.MA10=[[dic objectForKey:@"MA10"] stringValue];
            stockVolume.MA20=[[dic objectForKey:@"MA20"] stringValue];
            stockVolume.volume=[dic objectForKey:@"volume"];
            stockVolume.amount=[[dic objectForKey:@"amount"] stringValue];
            
            id value=[dic objectForKey:@"date"];
            NSDate *nd=[NSDate dateWithTimeIntervalSince1970:(float)[value floatValue]];
            NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSString *dateStr=[dateFormatter stringFromDate:nd];
            stockVolume.date=dateStr;
            [tempArray addObject:stockVolume];
        }
        self.stockArray=tempArray;
        
        //    套用第三方的方法来请求数据
        [self requestFinished];
        
        [self.progressHUD hide:YES];
        
    } errorBlock:^(NSError *error) {
        [MyHandle setUpMBProgressWithView:self.view Text:@"网络错误，请检查网络"];
        
    }];
    
}

- (void)backToStockHome:(UIButton *)button{
    //dismiss，模态回到stockHome
//    [UIView transitionFromView:self.view toView:self.parentViewController.view duration:1.0f options:UIViewAnimationOptionTransitionFlipFromRight completion:nil];
    
    self.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)changeSectionShow:(UIButton *)button{
    
    _simpleOrNot=!_simpleOrNot;
    if (_simpleOrNot==YES) {
        [button setTitle:@"详细" forState:UIControlStateNormal];
    }
    else{
        [button setTitle:@"简约" forState:UIControlStateNormal];
    }
    [self requestFinished];
}

- (void)bigClickButton:(UIButton *)button{
    NSInteger index=button.tag-1000;
    self.headControlView.nowLocation=index;
#warning button的点击事件: 进行网络请求，并展示
    
    //    if (index==0) {
    //        //请求分时图
    ////        [self.candleChart getSection:2].hidden = YES;
    ////        [self loadNewDataWithType:self.req_type freq:self.req_freq];
    //        _simpleOrNot=!_simpleOrNot;
    //        [self requestFinished];
    //    }
    if(index==0){
        //请求日K
        self.chartMode=1;
        self.req_type=@"day";
        [self loadNewDataWithType:self.req_type freq:self.req_freq];
    }
    else if(index==1){
        //请求周k
        self.chartMode=1;
        self.req_type=@"week";
        [self loadNewDataWithType:self.req_type freq:self.req_freq];
    }
    else{
        //请求月K
        self.chartMode=1;
        self.req_type=@"month";
        [self loadNewDataWithType:self.req_type freq:self.req_freq];
    }
}

-(void)initChart{
    NSMutableArray *padding = [NSMutableArray arrayWithObjects:@"10",@"10",@"10",@"10",nil];
    [self.candleChart setPadding:padding];
    NSMutableArray *secs = [[NSMutableArray alloc] init];
    [secs addObject:@"8"];
    [secs addObject:@"3"];
    [secs addObject:@"3"];
    [self.candleChart addSections:3 withRatios:secs];
    [self.candleChart getSection:2].hidden = YES;
    [[[self.candleChart sections] objectAtIndex:0] addYAxis:0];
    [[[self.candleChart sections] objectAtIndex:1] addYAxis:0];
    [[[self.candleChart sections] objectAtIndex:2] addYAxis:0];
    
    [self.candleChart getYAxis:2 withIndex:0].baseValueSticky = NO;
    [self.candleChart getYAxis:2 withIndex:0].symmetrical = NO;
    [self.candleChart getYAxis:0 withIndex:0].ext = 0.05;
    NSMutableArray *series = [[NSMutableArray alloc] init];
    NSMutableArray *secOne = [[NSMutableArray alloc] init];
    NSMutableArray *secTwo = [[NSMutableArray alloc] init];
    NSMutableArray *secThree = [[NSMutableArray alloc] init];
    
    
#pragma mark - secOne中加入了4个serie数据，secTwo中只有一个VOL数据，secThree在这里是空的 -
    //price
    NSMutableDictionary *serie = [[NSMutableDictionary alloc] init];
    NSMutableArray *data = [[NSMutableArray alloc] init];  //最小的真实数据源数组
    [serie setObject:@"price" forKey:@"name"];  //唯一标识符
    [serie setObject:@"Price" forKey:@"label"];  //label上显示的东西Price
    [serie setObject:data forKey:@"data"];
    [serie setObject:@"candle" forKey:@"type"];  //图形的类型，candle
    [serie setObject:@"0" forKey:@"yAxis"];
    [serie setObject:@"0" forKey:@"section"]; //第0区
    [serie setObject:@"249,222,170" forKey:@"color"];  //淡黄色
    [serie setObject:@"249,222,170" forKey:@"negativeColor"];
    [serie setObject:@"249,222,170" forKey:@"selectedColor"];
    [serie setObject:@"249,222,170" forKey:@"negativeSelectedColor"];
    [serie setObject:@"176,52,52" forKey:@"labelColor"];   //红色
    [serie setObject:@"77,143,42" forKey:@"labelNegativeColor"];  //绿色
    //Chart的大数据源(seires数组)要加上serie
    [series addObject:serie];
    //每个区的区数据源(secOnt)也要加上serie
    [secOne addObject:serie];  //加到第一个区里secOne
    [data release];
    [serie release];
    
    //MA10
    serie = [[NSMutableDictionary alloc] init];
    data = [[NSMutableArray alloc] init];
    [serie setObject:@"ma10" forKey:@"name"];
    [serie setObject:@"MA10" forKey:@"label"];
    [serie setObject:data forKey:@"data"];
    [serie setObject:@"line" forKey:@"type"];   //图的类型为线，line
    [serie setObject:@"0" forKey:@"yAxis"];
    [serie setObject:@"0" forKey:@"section"];
    [serie setObject:@"255,255,255" forKey:@"color"];
    [serie setObject:@"255,255,255" forKey:@"negativeColor"];
    [serie setObject:@"255,255,255" forKey:@"selectedColor"];
    [serie setObject:@"255,255,255" forKey:@"negativeSelectedColor"];
    [series addObject:serie];
    [secOne addObject:serie];
    [data release];
    [serie release];
    
    //MA30
    serie = [[NSMutableDictionary alloc] init];
    data = [[NSMutableArray alloc] init];
    [serie setObject:@"ma30" forKey:@"name"];
    [serie setObject:@"MA30" forKey:@"label"];
    [serie setObject:data forKey:@"data"];
    [serie setObject:@"line" forKey:@"type"];
    [serie setObject:@"0" forKey:@"yAxis"];
    [serie setObject:@"0" forKey:@"section"];
    [serie setObject:@"250,232,115" forKey:@"color"];
    [serie setObject:@"250,232,115" forKey:@"negativeColor"];
    [serie setObject:@"250,232,115" forKey:@"selectedColor"];
    [serie setObject:@"250,232,115" forKey:@"negativeSelectedColor"];
    [series addObject:serie];
    [secOne addObject:serie];
    [data release];
    [serie release];
    
    //MA60
    serie = [[NSMutableDictionary alloc] init];
    data = [[NSMutableArray alloc] init];
    [serie setObject:@"ma60" forKey:@"name"];
    [serie setObject:@"MA60" forKey:@"label"];
    [serie setObject:data forKey:@"data"];
    [serie setObject:@"line" forKey:@"type"];
    [serie setObject:@"0" forKey:@"yAxis"];
    [serie setObject:@"0" forKey:@"section"];
    [serie setObject:@"232,115,250" forKey:@"color"];
    [serie setObject:@"232,115,250" forKey:@"negativeColor"];
    [serie setObject:@"232,115,250" forKey:@"selectedColor"];
    [serie setObject:@"232,115,250" forKey:@"negativeSelectedColor"];
    [series addObject:serie];
    [secOne addObject:serie];
    [data release];
    [serie release];
    
    
    //VOL
    serie = [[NSMutableDictionary alloc] init];
    data = [[NSMutableArray alloc] init];
    [serie setObject:@"vol" forKey:@"name"];
    [serie setObject:@"VOL" forKey:@"label"];
    [serie setObject:data forKey:@"data"];
    [serie setObject:@"column" forKey:@"type"];
    [serie setObject:@"0" forKey:@"yAxis"];
    [serie setObject:@"1" forKey:@"section"];    //加到第一区里
    [serie setObject:@"0" forKey:@"decimal"];    //十进制为0?
    [serie setObject:@"176,52,52" forKey:@"color"];   //红色
    [serie setObject:@"77,143,42" forKey:@"negativeColor"];   //绿色
    [serie setObject:@"176,52,52" forKey:@"selectedColor"];
    [serie setObject:@"77,143,42" forKey:@"negativeSelectedColor"];
    [series addObject:serie];
#warning 这里是否可以加到secThree中，可能不行，因为secThree是画线图的
    [secTwo addObject:serie];
    [data release];
    [serie release];
    
    //candleChart init
    [self.candleChart setSeries:series];
    [series release];
    
    [[[self.candleChart sections] objectAtIndex:0] setSeries:secOne];
    [secOne release];
    [[[self.candleChart sections] objectAtIndex:1] setSeries:secTwo];
    [secTwo release];
    [[[self.candleChart sections] objectAtIndex:2] setSeries:secThree];
    
#pragma mark 这里就是让他实现可以点击换页,改成NO则不能点击换页
    [[[self.candleChart sections] objectAtIndex:2] setPaging:YES];
    [secThree release];
    
    //----
    //    NSString *indicatorsString =[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"indicators" ofType:@"json"] encoding:NSUTF8StringEncoding error:nil];
    
    //1.找文件路径
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"indicators" ofType:@"json"];
    //2.将文件中的数据转成NSData(二进制)类型
    NSData *fileData=[NSData dataWithContentsOfFile:filePath];
    //3.用系统的NSJsonSerialization，将NSData转=化成object
    //系统类
    NSArray *fileArray=[NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingAllowFragments error:nil];
    
#pragma mark - 这里是解析这个文件 -
    if(fileData != nil){
        //----
        //        NSArray *indicators = [indicatorsString objectFromJSONString];
        NSArray *indicators = fileArray;
        for(NSObject *indicator in indicators){
            if([indicator isKindOfClass:[NSArray class]]){
                NSMutableArray *arr = [[NSMutableArray alloc] init];
                for(NSDictionary *indic in indicator){
                    NSMutableDictionary *serie = [[NSMutableDictionary alloc] init];
                    [self setOptions:indic ForSerie:serie];
                    [arr addObject:serie];
                    [serie release];
                }
                [self.candleChart addSerie:arr];
                [arr release];
            }else{
                NSDictionary *indic = (NSDictionary *)indicator;
                NSMutableDictionary *serie = [[NSMutableDictionary alloc] init];
                //直接把json里的字典转化为serie字典格式
                //这里只把serie或者arr加到Chart的大数据源中，而没有给secThree加数据源
                [self setOptions:indic ForSerie:serie];
                [self.candleChart addSerie:serie];
                [serie release];
            }
        }
    }
    
#pragma mark - 给画图的终点加动画，应该是画个大原点
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 10.0;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:2.0f];
    [self.candleChart.layer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
}

-(void)setOptions:(NSDictionary *)options ForSerie:(NSMutableDictionary *)serie;{
    [serie setObject:[options objectForKey:@"name"] forKey:@"name"];
    [serie setObject:[options objectForKey:@"label"] forKey:@"label"];
    [serie setObject:[options objectForKey:@"type"] forKey:@"type"];
    [serie setObject:[options objectForKey:@"yAxis"] forKey:@"yAxis"];
    [serie setObject:[options objectForKey:@"section"] forKey:@"section"];
    [serie setObject:[options objectForKey:@"color"] forKey:@"color"];
    [serie setObject:[options objectForKey:@"negativeColor"] forKey:@"negativeColor"];
    [serie setObject:[options objectForKey:@"selectedColor"] forKey:@"selectedColor"];
    [serie setObject:[options objectForKey:@"negativeSelectedColor"] forKey:@"negativeSelectedColor"];
}

//----
#pragma mark - 通过button的点击（tag值的不同）来请求不同的数据 -
/*
 -(void)buttonPressed:(id)sender{
 UIButton *btn = (UIButton *)sender;
 int index = btn.tag;
 
 if(index !=2){
 CGContextRef context = UIGraphicsGetCurrentContext();
 [UIView beginAnimations:nil context:context];
 [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
 [UIView setAnimationDuration:0.3];
 CGRect rect = [self.candleChartFreqView frame];
 rect.origin.y =  - 160;
 [self.candleChartFreqView setFrame:rect];
 [UIView commitAnimations];
 }
 
 if(index>=21 && index<=28){
 for (UIView *subview in self.candleChartFreqView.subviews){
 UIButton *btn = (UIButton *)subview;
 btn.selected = NO;
 }
 }
 btn.selected = YES;
 
 switch (index) {
 case 1:{
 UIButton *sel = (UIButton *)[self.toolBar viewWithTag:2];
 sel.selected = NO;
 self.chartMode  = 0;
 self.req_freq   = @"1m";
 self.req_type   = @"T";
 [self getData];
 break;
 }
 case 2:{
 UIButton *sel = (UIButton *)[self.toolBar viewWithTag:1];
 sel.selected = NO;
 CGContextRef context = UIGraphicsGetCurrentContext();
 [UIView beginAnimations:nil context:context];
 [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
 [UIView setAnimationDuration:0.3];
 CGRect rect = [self.candleChartFreqView frame];
 if(rect.origin.y == 0){
 rect.origin.y = - 160;
 [self.candleChartFreqView setFrame:rect];
 }else{
 rect.origin.y =  0;
 [self.candleChartFreqView setFrame:rect];
 btn.selected = NO;
 sel.selected = NO;
 }
 [UIView commitAnimations];
 break;
 }
 case 26:{
 UIButton *sel = (UIButton *)[self.toolBar viewWithTag:2];
 sel.selected = NO;
 self.chartMode  = 1;
 self.req_freq   = @"d";
 self.req_type   = @"H";
 [self getData];
 break;
 break;
 }
 case 27:{
 UIButton *sel = (UIButton *)[self.toolBar viewWithTag:2];
 sel.selected = NO;
 self.chartMode  = 1;
 self.req_freq   = @"w";
 self.req_type   = @"H";
 [self getData];
 break;
 
 }
 case 28:{
 UIButton *sel = (UIButton *)[self.toolBar viewWithTag:2];
 sel.selected = NO;
 self.chartMode  = 1;
 self.req_freq   = @"m";
 self.req_type   = @"H";
 [self getData];
 break;
 
 }
 case 50:{
 UIGraphicsBeginImageContext(self.candleChart.bounds.size);
 [self.candleChart.layer renderInContext:UIGraphicsGetCurrentContext()];
 UIImage *anImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 UIImageWriteToSavedPhotosAlbum(anImage,nil,nil,nil);
 break;
 }
 default:
 break;
 }
 
 }
 */

//---- 一进来添加观察者
//- (void)doNotification:(NSNotification *)notification{
//    UIButton *sel = (UIButton *)[self.toolBar viewWithTag:1];
//    [self buttonPressed:sel];
//}

//---- 关于searchBar
/*
 //- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
 //	NSMutableArray *data = [self.autoCompleteDelegate.items mutableCopy];
 //    self.autoCompleteDelegate.selectedItems = data;
 //	[data release];
 //    self.autoCompleteView.hidden = NO;
 //
 //	if([self isCodesExpired]){
 ////	    [self getAutoCompleteData];
 //	}
 //
 //	CGContextRef context = UIGraphicsGetCurrentContext();
 //	[UIView beginAnimations:nil context:context];
 //	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
 //	[UIView setAnimationDuration:0.2];
 //	CGRect rect = [self.autoCompleteView frame];
 //	rect.size.height = 300;
 //	[self.autoCompleteView setFrame:rect];
 //	[UIView commitAnimations];
 //}
 //
 //- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
 //	[self.autoCompleteDelegate.selectedItems removeAllObjects];
 //    for(NSArray *item in self.autoCompleteDelegate.items){
 //	    if([[item objectAtIndex:0] hasPrefix:searchText]){
 //			[self.autoCompleteDelegate.selectedItems addObject:item];
 //		}
 //	}
 //	[self.autoCompleteView reloadData];
 //}
 
 //- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
 //	CGRect rect = [self.autoCompleteView frame];
 //	rect.size.height = 0;
 //	[self.autoCompleteView setFrame:rect];
 //	self.autoCompleteView.hidden = YES;
 //    if(![searchBar.text isEqualToString:@""]){
 //
 //#pragma mark 这里得到股票的请求代码
 //        self.req_security_id = [[[[[searchBar text] componentsSeparatedByString:@"（"] objectAtIndex:1] componentsSeparatedByString:@"）"] objectAtIndex:0];
 //        [self getData];
 //    }
 //}
 
 //- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar{
 //    NSLog(@"CancelButtonClicked");
 //}
 //
 - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
 [searchBar resignFirstResponder];
 #pragma mark 这里得到股票的请求代码
 self.req_security_id = [[[[[searchBar text] componentsSeparatedByString:@"（"] objectAtIndex:1] componentsSeparatedByString:@"）"] objectAtIndex:0];
 [self getData];
 }
 
 //-(BOOL)isCodesExpired{
 //	NSDate *date = [NSDate date];
 //	double now = [date timeIntervalSince1970];
 //	double last = now;
 //	NSString *autocompTime = (NSString *)[ResourceHelper  getUserDefaults:@"autocompTime"];
 //	if(autocompTime!=nil){
 //		last = [autocompTime doubleValue];
 //		if(now - last >3600*8){
 //		    return YES;
 //		}else{
 //		    return NO;
 //		}
 //    }else{
 //	    return YES;
 //	}
 //}
 */

//----
#pragma mark - 获取本地各股票信息，便于搜索 -
//-(void)getAutoCompleteData{
//    NSString *securities =[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"securities" ofType:@"json"] encoding:NSUTF8StringEncoding error:nil];
//    NSMutableArray *data = [securities mutableObjectFromJSONString];
//    self.autoCompleteDelegate.items = data;
//}

#pragma mark - 原来的getData，主要是设置section是否显示，同时拼接请求网址
/*
 -(void)getData{
 //
 //    self.status.text = @"Loading...";
 #pragma mark  通过chartMode来判断第二个区是否显示，如果设置为NO，则它就不显示了
 if(chartMode == 0){
 [self.candleChart getSection:2].hidden = YES;
 
 }else{
 [self.candleChart getSection:2].hidden = NO;
 
 //如果添加上这句，这个区就不显示了
 //                [self.candleChart getSection:0].hidden=YES;
 //        [self.candleChart getSection:1].hidden=YES;
 //        [self.candleChart getSection:2].hidden=YES;
 }
 
 #pragma mark - 这里就开始请求数据了 -
 NSString *reqURL = [[NSString alloc] initWithFormat:self.req_url,self.req_security_id,self.req_freq];
 //打印请求网址
 NSLog(@"url:%@",reqURL);
 
 NSURL *url = [NSURL URLWithString:[reqURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
 [reqURL release];
 
 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
 //	[request setTimeOutSeconds:5];
 [request setDelegate:self];
 [request startAsynchronous];
 }
 */

#pragma mark - 请求成功后布局，并传数据 -
- (void)requestFinished
{
    
#pragma mark 用于切换3视图是否隐藏
    if(_simpleOrNot == YES){
        [self.candleChart getSection:2].hidden = YES;
        
    }else{
        [self.candleChart getSection:2].hidden = NO;
    }
    
    //----
    //    self.status.text = @"";
    NSMutableArray *data =[[NSMutableArray alloc] init];
    NSMutableArray *category =[[NSMutableArray alloc] init];
    
    //-----以前的数据都是一行行的字符串
    //    NSString *content = [request responseString];
    //    NSLog(@"content=%@",content);
    //    NSArray *lines = [content componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    NSInteger idx;
    for (idx = self.stockArray.count-1; idx > 0; idx--) {
        
        //-----  判断如果没有数据，就继续运行
        //        NSString *line = [lines objectAtIndex:idx];
        //        if([line isEqualToString:@""]){
        //            continue;
        //        }
        
#pragma 请求下来的数据样式
        //一行数据样式,注意这里请求到的Volume都为000，所以Volume的数据就看不到了
        //Date,       Open,     High,     Low,   Close,   Volume,  Adj Close
        //2015-07-20,13202.40,13754.50,13202.40,13518.50,   000,   13518.50
        
        //------
        //        NSArray   *arr = [line componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
        //        [category addObject:[arr objectAtIndex:0]];
        
        StockVolume *stockVolume=self.stockArray[idx];
        //        这里给category加的是date
        [category addObject:stockVolume.date];
        
        NSMutableArray *item =[[NSMutableArray alloc] init];
        //        [item addObject:[arr objectAtIndex:1]]; //Open
        //        [item addObject:[arr objectAtIndex:4]]; //Close
        //        [item addObject:[arr objectAtIndex:2]]; //High
        //        [item addObject:[arr objectAtIndex:3]]; //Low
        //        [item addObject:[arr objectAtIndex:5]]; //Volume
        [item addObject: stockVolume.open];
        [item addObject: stockVolume.close];
        [item addObject: stockVolume.high];
        [item addObject: stockVolume.low];
        [item addObject: stockVolume.volume];
        
#pragma mark data数组中的元素都是item数组(这里可以定义为stock的model)，然后item数组中存放:最高价，最低价，开盘价，收盘价
        [data addObject:item];
        [item release];
    }
    
    if(data.count==0){
        return;
    }
    
    //这里判断，chartMode==0,即为line的模型，而不是==1时的candle类型
#pragma mark 这里的意思是要清空数据源，另外判断该股票是否处于休市状态
    //------他涉及到的self.timer,self.req_type（不同于我请求用的req_type），self.lastTime 搜索全文都没用到
    
    //    if (chartMode == 0) {
    //        if([self.req_type isEqualToString:@"T"]){
    //            if(self.timer != nil)
    //                [self.timer invalidate];
    //
    //            [self.candleChart reset];
    //            [self.candleChart clearData];
    //            [self.candleChart clearCategory];
    //
    //            if([self.req_freq hasSuffix:@"m"]){
    //                self.req_type = @"L";
    //                //				self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(getData) userInfo:nil repeats:YES];
    //            }
    //        }else{
    //            NSString *time = [category objectAtIndex:0];
    //            if([time isEqualToString:self.lastTime]){
    //                if([time hasSuffix:@"1500"]){
    //                    if(self.timer != nil)
    //                        [self.timer invalidate];
    //                }
    //                return;
    //            }
    //            if ([time hasSuffix:@"1130"] || [time hasSuffix:@"1500"]) {
    //                if(self.tradeStatus == 1){
    //                    self.tradeStatus = 0;
    //                }
    //            }else{
    //                self.tradeStatus = 1;
    //            }
    //        }
    //    }else{
    //        if(self.timer != nil)
    //            [self.timer invalidate];
    //        [self.candleChart reset];
    //        [self.candleChart clearData];
    //        [self.candleChart clearCategory];
    //    }
    //
    //    self.lastTime = [category lastObject];
    
    //    if(self.timer != nil)
    //        [self.timer invalidate];
    [self.candleChart reset];
    [self.candleChart clearData];
    [self.candleChart clearCategory];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
#warning 数据部分来了!!!
#pragma mark - 初始化数据，加入字典 -
    [self generateData:dic From:data];
#pragma mark - 转化为Chart的数据源 -
    [self setData:dic];
    [dic release];
    
    //    这里为什么要筛选来放弃一些数据呢？
    if(chartMode == 0){
        //线的时候直接给
        [self setCategory:category];
    }else{
        //candle的时候，放弃前60条数据
        NSMutableArray *cate = [[NSMutableArray alloc] init];
        for(int i=60;i<category.count;i++){
            [cate addObject:[category objectAtIndex:i]];
        }
        [self setCategory:cate];
        [cate release];
    }
    
#pragma mark - 调用画图功能，这里是 -
    [self.candleChart setNeedsDisplay];
}

-(void)generateData:(NSMutableDictionary *)dic From:(NSArray *)data{
    
    //还是要判断是line 类型，还是candle类型
    if(self.chartMode == 1){ //1为candle类型
        
        //price ： 包含了high,low,open,close,volume
        NSMutableArray *price = [[NSMutableArray alloc] init];
        
#warning 为什么不要前60条数据呢
        for(int i = 60;i < data.count;i++){
            [price addObject: [data objectAtIndex:i]];
        }
        [dic setObject:price forKey:@"price"];
        [price release];
        
        //VOL
        NSMutableArray *vol = [[NSMutableArray alloc] init];
        for(int i = 60;i < data.count;i++){
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",[[[data objectAtIndex:i] objectAtIndex:4] floatValue]/100]];
            [vol addObject:item];
            [item release];
        }
        [dic setObject:vol forKey:@"vol"];
        [vol release];
        
        //MA 10
        NSMutableArray *ma10 = [[NSMutableArray alloc] init];
        for(int i = 60;i < data.count;i++){
            float val = 0;
            for(int j=i;j>i-10;j--){
                val += [[[data objectAtIndex:j] objectAtIndex:1] floatValue];
            }
            val = val/10;
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",val]];
            [ma10 addObject:item];
            [item release];
        }
        [dic setObject:ma10 forKey:@"ma10"];
        [ma10 release];
        
        //MA 30
        NSMutableArray *ma30 = [[NSMutableArray alloc] init];
        for(int i = 60;i < data.count;i++){
            float val = 0;
            for(int j=i;j>i-30;j--){
                val += [[[data objectAtIndex:j] objectAtIndex:1] floatValue];
            }
            val = val/30;
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",val]];
            [ma30 addObject:item];
            [item release];
        }
        [dic setObject:ma30 forKey:@"ma30"];
        [ma30 release];
        
        //MA 60
        NSMutableArray *ma60 = [[NSMutableArray alloc] init];
        for(int i = 60;i < data.count;i++){
            float val = 0;
            for(int j=i;j>i-60;j--){
                val += [[[data objectAtIndex:j] objectAtIndex:1] floatValue];
            }
            val = val/60;
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",val]];
            [ma60 addObject:item];
            [item release];
        }
        [dic setObject:ma60 forKey:@"ma60"];
        [ma60 release];
        
        //RSI6
        NSMutableArray *rsi6 = [[NSMutableArray alloc] init];
        for(int i = 60;i < data.count;i++){
            float incVal  = 0;
            float decVal = 0;
            float rs = 0;
            for(int j=i;j>i-6;j--){
                float interval = [[[data objectAtIndex:j] objectAtIndex:1] floatValue]-[[[data objectAtIndex:j] objectAtIndex:0] floatValue];
                if(interval >= 0){
                    incVal += interval;
                }else{
                    decVal -= interval;
                }
            }
            
            rs = incVal/decVal;
            float rsi =100-100/(1+rs);
            
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",rsi]];
            [rsi6 addObject:item];
            [item release];
            
        }
        [dic setObject:rsi6 forKey:@"rsi6"];
        [rsi6 release];
        
        //RSI12
        NSMutableArray *rsi12 = [[NSMutableArray alloc] init];
        for(int i = 60;i < data.count;i++){
            float incVal  = 0;
            float decVal = 0;
            float rs = 0;
            for(int j=i;j>i-12;j--){
                float interval = [[[data objectAtIndex:j] objectAtIndex:1] floatValue]-[[[data objectAtIndex:j] objectAtIndex:0] floatValue];
                if(interval >= 0){
                    incVal += interval;
                }else{
                    decVal -= interval;
                }
            }
            
            rs = incVal/decVal;
            float rsi =100-100/(1+rs);
            
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",rsi]];
            [rsi12 addObject:item];
            [item release];
        }
        [dic setObject:rsi12 forKey:@"rsi12"];
        [rsi12 release];
        
        //WR
        NSMutableArray *wr = [[NSMutableArray alloc] init];
        for(int i = 60;i < data.count;i++){
            float h  = [[[data objectAtIndex:i] objectAtIndex:2] floatValue];
            float l = [[[data objectAtIndex:i] objectAtIndex:3] floatValue];
            float c = [[[data objectAtIndex:i] objectAtIndex:1] floatValue];
            for(int j=i;j>i-10;j--){
                if([[[data objectAtIndex:j] objectAtIndex:2] floatValue] > h){
                    h = [[[data objectAtIndex:j] objectAtIndex:2] floatValue];
                }
                
                if([[[data objectAtIndex:j] objectAtIndex:3] floatValue] < l){
                    l = [[[data objectAtIndex:j] objectAtIndex:3] floatValue];
                }
            }
            
            float val = (h-c)/(h-l)*100;
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",val]];
            [wr addObject:item];
            [item release];
        }
        [dic setObject:wr forKey:@"wr"];
        [wr release];
        
        //KDJ
        NSMutableArray *kdj_k = [[NSMutableArray alloc] init];
        NSMutableArray *kdj_d = [[NSMutableArray alloc] init];
        NSMutableArray *kdj_j = [[NSMutableArray alloc] init];
        float prev_k = 50;
        float prev_d = 50;
        float rsv = 0;
        for(int i = 60;i < data.count;i++){
            float h  = [[[data objectAtIndex:i] objectAtIndex:2] floatValue];
            float l = [[[data objectAtIndex:i] objectAtIndex:3] floatValue];
            float c = [[[data objectAtIndex:i] objectAtIndex:1] floatValue];
            for(int j=i;j>i-10;j--){
                if([[[data objectAtIndex:j] objectAtIndex:2] floatValue] > h){
                    h = [[[data objectAtIndex:j] objectAtIndex:2] floatValue];
                }
                
                if([[[data objectAtIndex:j] objectAtIndex:3] floatValue] < l){
                    l = [[[data objectAtIndex:j] objectAtIndex:3] floatValue];
                }
            }
            
            if(h!=l)
                rsv = (c-l)/(h-l)*100;
            float k = 2*prev_k/3+1*rsv/3;
            float d = 2*prev_d/3+1*k/3;
            float j = d+2*(d-k);
            
            prev_k = k;
            prev_d = d;
            
            NSMutableArray *itemK = [[NSMutableArray alloc] init];
            [itemK addObject:[@"" stringByAppendingFormat:@"%f",k]];
            [kdj_k addObject:itemK];
            [itemK release];
            NSMutableArray *itemD = [[NSMutableArray alloc] init];
            [itemD addObject:[@"" stringByAppendingFormat:@"%f",d]];
            [kdj_d addObject:itemD];
            [itemD release];
            NSMutableArray *itemJ = [[NSMutableArray alloc] init];
            [itemJ addObject:[@"" stringByAppendingFormat:@"%f",j]];
            [kdj_j addObject:itemJ];
            [itemJ release];
        }
        [dic setObject:kdj_k forKey:@"kdj_k"];
        [dic setObject:kdj_d forKey:@"kdj_d"];
        [dic setObject:kdj_j forKey:@"kdj_j"];
        [kdj_k release];
        [kdj_d release];
        [kdj_j release];
        
        //VR
        NSMutableArray *vr = [[NSMutableArray alloc] init];
        for(int i = 60;i < data.count;i++){
            float inc = 0;
            float dec = 0;
            float eq  = 0;
            for(int j=i;j>i-24;j--){
                float o = [[[data objectAtIndex:j] objectAtIndex:0] floatValue];
                float c = [[[data objectAtIndex:j] objectAtIndex:1] floatValue];
                
                if(c > o){
                    inc += [[[data objectAtIndex:j] objectAtIndex:4] intValue];
                }else if(c < o){
                    dec += [[[data objectAtIndex:j] objectAtIndex:4] intValue];
                }else{
                    eq  += [[[data objectAtIndex:j] objectAtIndex:4] intValue];
                }
            }
            
            float val = (inc+1*eq/2)/(dec+1*eq/2);
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",val]];
            [vr addObject:item];
            [item release];
        }
        [dic setObject:vr forKey:@"vr"];
        [vr release];
        
    }else{
#pragma mark - 如果加入分时图，则下方的price需要删除，后面两个函数也要修改
        //price
        NSMutableArray *price = [[NSMutableArray alloc] init];
        for(int i = 0;i < data.count;i++){
            [price addObject: [data objectAtIndex:i]];
        }
        [dic setObject:price forKey:@"price"];
        [price release];
        
        //VOL
        NSMutableArray *vol = [[NSMutableArray alloc] init];
        for(int i = 0;i < data.count;i++){
            NSMutableArray *item = [[NSMutableArray alloc] init];
            [item addObject:[@"" stringByAppendingFormat:@"%f",[[[data objectAtIndex:i] objectAtIndex:4] floatValue]/100]];
            [vol addObject:item];
            [item release];
        }
        [dic setObject:vol forKey:@"vol"];
        [vol release];
        
    }
}

#pragma mark - 给Chart.series的大数据源中，的data值加入这些真正的数据 -
-(void)setData:(NSDictionary *)dic{
    
    
    [self.candleChart appendToData:[dic objectForKey:@"price"] forName:@"price"];
    [self.candleChart appendToData:[dic objectForKey:@"vol"] forName:@"vol"];
    
    [self.candleChart appendToData:[dic objectForKey:@"ma10"] forName:@"ma10"];
    [self.candleChart appendToData:[dic objectForKey:@"ma30"] forName:@"ma30"];
    [self.candleChart appendToData:[dic objectForKey:@"ma60"] forName:@"ma60"];
    
    [self.candleChart appendToData:[dic objectForKey:@"rsi6"] forName:@"rsi6"];
    [self.candleChart appendToData:[dic objectForKey:@"rsi12"] forName:@"rsi12"];
    
    [self.candleChart appendToData:[dic objectForKey:@"wr"] forName:@"wr"];
    [self.candleChart appendToData:[dic objectForKey:@"vr"] forName:@"vr"];
    
    [self.candleChart appendToData:[dic objectForKey:@"kdj_k"] forName:@"kdj_k"];
    [self.candleChart appendToData:[dic objectForKey:@"kdj_d"] forName:@"kdj_d"];
    [self.candleChart appendToData:[dic objectForKey:@"kdj_j"] forName:@"kdj_j"];
    
    NSMutableDictionary *serie = [self.candleChart getSerie:@"price"];
    if(serie == nil)
        return;
    if(self.chartMode == 1){
        [serie setObject:@"candle" forKey:@"type"];
    }else{
        [serie setObject:@"line" forKey:@"type"];
    }
}

-(void)setCategory:(NSArray *)category{
    [self.candleChart appendToCategory:category forName:@"price"];
    [self.candleChart appendToCategory:category forName:@"line"];
    
}

//- (void)requestFailed:(ASIHTTPRequest *)request{
//    self.status.text = @"Error!";
//}

// 已经被废弃的方法
// - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation NS_DEPRECATED_IOS(2_0, 6_0);
//
//  新方法 New Autorotation support.
// - (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0);
//
//
// - (NSUInteger)supportedInterfaceOrientations NS_AVAILABLE_IOS(6_0);
//  Returns interface orientation masks.
// 重写这个方法，就能实现，一点击controller上的某个view，这个view就显示为你反悔的状态
// - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation NS_AVAILABLE_IOS(6_0);

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
//    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
//}
//
#warning 这里更改屏幕横竖屏
//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
//    return UIInterfaceOrientationLandscapeLeft;
//}

#pragma mark - 旋转屏幕 -
//该方法也已经失效，具体再查API
//- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration{
//
//}
//用这个方法来替换
//- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
//
//}


#pragma mark - 在控制器disappear 中，确保NSTimer 被终止 -
- (void)viewWillDisappear:(BOOL)animated{
    [self.timer invalidate];
}

#pragma mark - dealloc -
- (void)dealloc {
    [super dealloc];
    [candleChart release];
    [req_security_id release];
    [timer release];
    [lastTime release];
    [req_freq release];
    [req_type release];
    [req_security_id release];
    [_stockArray release];
    [_headControlView release];
    [_code release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
